// local.js
// invoke local interface using electron ipc or local web server
import axios from 'axios';
const LOCAL_BASE_URL = import.meta.env.VITE_APP_LOCAL_SERVER_URL;

class LocalAPI {
    constructor() {
        this.electron_env = window.electronAPI ? true : false;
        this.use_post_method = true;
        this.use_local_server = this.electron_env ? false : true;
    }

    // 获取接口的get url地址（特别针对加载本地图片）
    api_url(method, params) {
        let base_url = `${LOCAL_BASE_URL}/${method}`;
        let query = Object.entries(params)
            .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
            .join('&');
        return `${base_url}?${query}`;
    }

    // 通过 method（字符串）和 params 调用本地的 API 接口
    // 判断 window.electronAPI 是否可用，否则直接选择使用 Local Web Server
    async invoke(method, params) {
        if (this.electron_env && !this.use_local_server) {
            try {
                return await window.electronAPI[method](params);
            } catch (error) {
                console.error(`Error invoking electron API [${method}]:`, error.message);
                throw error;
            }
        } else {
            // console.log(`local invoke method = ${method}, params = `, params);
            try {
                if (this.use_post_method) {
                    return await this._localPost(method, params);
                } else {
                    return await this._localGet(method, params);
                }
            } catch (error) {
                console.error('Error invoking local API:', error.message);
                throw error;
            }
        }
    }

    // 发起 POST 请求
    async _localPost(method, params) {
        // console.log('LOCAL_BASE_URL = ', LOCAL_BASE_URL);
        try {
            const response = await axios.post(`${LOCAL_BASE_URL}/${method}`, params);
            return response.data;
        } catch (error) {
            console.error(`Error invoking local API ${method} with POST: `, error.message);
            // throw error;
        }
    }

    // 发起 GET 请求
    async _localGet(method, params) {
        try {
            const response = await axios.get(`${LOCAL_BASE_URL}/${method}`, {
                params,
                paramsSerializer: (params) => {
                    return Object.entries(params)
                        .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                        .join('&');
                }
            });
            return response.data;
        } catch (error) {
            console.error('Error invoking local API with GET:', error.message);
            throw error;
        }
    }
}

export { LocalAPI };
